package com.fhyc.service.impl;

import com.fhyc.dao.SoInBusbarMapper;
import com.fhyc.dto.BusBarNaviDto;
import com.fhyc.dto.BusTreeDto;
import com.fhyc.service.BusBarService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BusBarServiceImpl implements BusBarService {

    @Resource
    private SoInBusbarMapper soInBusbarMapper;


    @Override
    public List<BusBarNaviDto> getBusBarNaviTree(String name, List<Integer> voltages) {
        List<BusTreeDto> resultSet = soInBusbarMapper.getBusBarNaviTree(name, voltages);
        // 构建树结构
        List<BusBarNaviDto> newTree = deepDeduplicate(buildTree(resultSet), new HashSet<>());
        // 过滤没有子节点的母节点
        //tree = filterEmptyNonLeafNodes(tree);
        //removePrefixFromTree(tree);
        if (!StringUtils.isBlank(name)) {
            // 名称模糊查询
            return filterTreeByName(newTree, name);
        } else {
            return newTree;
        }
    }

    private List<BusBarNaviDto> deepDeduplicate(List<BusBarNaviDto> buildTree, Set<String> seenIds) {
        if (buildTree == null || buildTree.isEmpty()) {
            return Collections.emptyList();
        }
        List<BusBarNaviDto> result = new ArrayList<>();
        for (BusBarNaviDto node : buildTree) {
            if (seenIds.add(node.getId())) {
                List<BusBarNaviDto> children = deepDeduplicate(node.getChildren(), seenIds);
                BusBarNaviDto newNode = new BusBarNaviDto(node.getId(), node.getName(), node.getType());
                newNode.setChildren(children);
                result.add(newNode);
            }
        }
        return result;
    }

    /**
     * 递归过滤掉没有子节点的非叶子节点（保留最后一层的子节点）
     */
    private List<BusBarNaviDto> filterEmptyNonLeafNodes(List<BusBarNaviDto> tree) {
        if (tree == null || tree.isEmpty()) {
            return new ArrayList<>();
        }

        // 遍历树的每个节点
        return tree.stream()
                .map(node -> {
                    // 如果节点有子节点，递归过滤其子节点
                    if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                        node.setChildren(filterEmptyNonLeafNodes(node.getChildren()));
                    }
                    // 如果子节点为空，且当前节点本身不是叶子节点（type不为4），则移除该节点
                    if ((node.getChildren() == null || node.getChildren().isEmpty()) && node.getType() != 3) {
                        return null;  // 标记该节点为要移除
                    }
                    return node;
                })
                .filter(Objects::nonNull)  // 移除被标记为 null 的节点
                .collect(Collectors.toList());
    }

    public void removePrefixFromTree(List<BusBarNaviDto> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        for (BusBarNaviDto node : nodes) {
            String idWithPrefix = node.getId().toString();
            String idWithOutPrefix = idWithPrefix.replaceFirst("^[^_]*_", "");
            node.setId(idWithOutPrefix);
            removePrefixFromTree(node.getChildren());
        }
    }

    /**
     *  过滤树结构，根据名称模糊查询
     * @param nodes
     * @param queryName
     * @return
     */
    public static List<BusBarNaviDto> filterTreeByName(List<BusBarNaviDto> nodes, String queryName) {
        List<BusBarNaviDto> filteredNodes = new ArrayList<>();

        for (BusBarNaviDto node : nodes) {
            // 递归过滤子节点
            List<BusBarNaviDto> filteredChildren = filterTreeByName(node.getChildren(), queryName);

            // 如果节点名称匹配或有子节点匹配，则保留节点
            if (node.getName().contains(queryName) || !filteredChildren.isEmpty()) {
                BusBarNaviDto newNode = new BusBarNaviDto(node.getId(), node.getName(), node.getType());
                newNode.setChildren(filteredChildren);
                filteredNodes.add(newNode);
            }
        }
        return filteredNodes;
    }


    /**
     * 构建树结构的方法
     *
     * @param resultSet
     * @return
     */
    public static List<BusBarNaviDto> buildTree(List<BusTreeDto> resultSet) {
        Map<String, BusBarNaviDto> nodeMap = new HashMap<>();
        List<BusBarNaviDto> roots = new ArrayList<>();

        for (BusTreeDto row : resultSet) {
            String id = row.getId();
            //log.info("id:" + id);
            String name = row.getName();
            int dataType = Integer.parseInt(row.getDataType());
            BusBarNaviDto node = new BusBarNaviDto(id, name, dataType);
            nodeMap.put(id, node);
            //log.info(nodeMap.toString());
        }

        // 遍历结果集，构建节点并放入map
        for (BusTreeDto row : resultSet) {
            String id = row.getId();
            String parentId = row.getParentId();
            BusBarNaviDto node = nodeMap.get(id);
            // if (parentId.equals("area_")) {
            roots.add(node);
            // } else {
            BusBarNaviDto parentNode = nodeMap.get(parentId);
            if (parentNode != null) {
                parentNode.addChild(node);
                // }
            }
        }

        // 排序根节点及其子节点
        sortTree(roots);
        return roots;

    }

    /**
     * 排序树节点
     *
     * @param nodes
     */
    public static void sortTree(List<BusBarNaviDto> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }

        // 排序节点，先按dataType排序，再按id排序
        nodes.sort(Comparator.comparingInt(BusBarNaviDto::getType));
//                .thenComparingInt(BusBarNaviDto::getId));

        // 递归排序子节点
        for (BusBarNaviDto node : nodes) {
            sortTree(node.getChildren());
        }
    }

}
